// 面向对象  ，构造函数改写；

function Enlarge(showEle,maskEle,boxEle,enlargeEle,smallImgEles,showImg){
    this.showEle = showEle;
    this.maskEle = maskEle;
    this.enlargeEle = enlargeEle;
    this.boxEle = boxEle;

    this.smallImgEles = smallImgEles;
    this.showImg = showImg;


    this.sx = 0;
    this.sy = 0;
    this.moveFn();
    this.showOrhide();
    this.switchImg();
}

// 放大镜的移动
Enlarge.prototype.moveFn = function(){
    this.showEle.onmousemove =  (e)=> {
        // 显示遮罩层 
        this.maskEle.style.display = "block";
        // console.log(boxEle.offsetLeft);
        // 获取鼠标相对于浏览器的位置；
        var x = e.clientX - this.boxEle.offsetLeft;
        var y = e.clientY - this.boxEle.offsetTop;
    
        // 把遮罩层设置到x 和y的位置
        let sx = x - this.maskEle.offsetWidth/2;
        let sy = y - this.maskEle.offsetHeight/2;
        this.sx = sx;
        this.sy = sy;
        // 区域判断 
        this.limitArae(sx,sy);

        console.log(this.sx);
        console.log(this.sy);
        this.maskEle.style.left = this.sx  + "px";
        this.maskEle.style.top = this.sy + "px";
    
        // 计算 x = sx  y  = sy  
        var showW = this.showEle.offsetWidth;
        var showH = this.showEle.offsetHeight;
        
        let str = getComputedStyle(this.enlargeEle)['background-size'];
        // console.log(str);
        var arr = str.split(" ");
        // console.log(arr);
        var bw = parseInt(arr[0]);
        var bh = parseInt(arr[1]);
    
        var xx = (this.sx/showW)*bw;
        var yy = (this.sy/showH)*bh;
        this.enlargeEle.style.backgroundPosition = `-${xx}px -${yy}px`;
    }
}

// 放大镜的显示和隐藏
Enlarge.prototype.showOrhide = function(){
    this.showEle.onmouseenter = ()=>{
            this.enlargeEle.style.display = "block";
        }
        
        this.showEle.onmouseleave =  ()=> {
            this.maskEle.style.display = "none";
            this.enlargeEle.style.display = "none";
        }
}

// 区域判断 

Enlarge.prototype.limitArae = function(sx,sy){
    if(sx<0){
        this.sx = 0;
    }

    // 上边边界
    if(sy<0){
        this.sy = 0;
    }

    // 右边边界 
    if(sx>this.showEle.offsetWidth-this.maskEle.offsetWidth){
        this.sx = this.showEle.offsetWidth-this.maskEle.offsetWidth;
    }

    // 下边的边界
    if(sy>this.showEle.offsetHeight-this.maskEle.offsetHeight){
        this.sy = this.showEle.offsetHeight-this.maskEle.offsetHeight;
    }
}


// 放大镜切换效果；
Enlarge.prototype.switchImg = function(){

 this.smallImgEles.forEach((img,key)=>{
    img.onclick = ()=>{
        console.log(key);
        // 改变上面的图；
        this.showImg.src = `./imgs/${key+1}.jpg`;
        // 改变放大区域的图；
        this.enlargeEle.style.backgroundImage = `url(./imgs/${key+1}.big.jpg)`;
    }
})
}












